import { Check, Mic, Pause, Play } from "lucide-vue-next";
import { defineComponent, ref } from "vue";
import Button from "@/components/Button";
import useAudioRecorder from "@/hooks/audio-recorder";
import useKeysPress from "@/hooks/keys-press";

const RecorderView = defineComponent({
  setup: () => {
    const audioUrl = ref<string | undefined>(undefined);

    const audio = useAudioRecorder({
      onOk(audio) {
        const url = URL.createObjectURL(audio);
        audioUrl.value = url;
      },
    });

    const handleClick = () => {
      switch (audio.status.value) {
        case "inactive":
          audio.start();
          audioUrl.value = undefined;
          break;
        default:
          audio.stop();
          break;
      }
    };

    const handlePause = () => {
      switch (audio.status.value) {
        case "recording":
          audio.pause();
          break;
        case "paused":
          audio.resume();
          break;
      }
    };

    const keys = useKeysPress({
      key1: "m",
      key2: "n",
      onAllPress: handleClick,
    });

    return () => (
      <div>
        <div class="p-4 flex gap-4">
          <Button shape="circle" variant="outline" onClick={handleClick}>
            {audio.status.value === "inactive" ? <Mic size={18} /> : <Check size={18} />}
          </Button>
          <Button shape="circle" variant="outline" onClick={handlePause} disabled={audio.status.value === "inactive"}>
            {audio.status.value === "recording" ? <Pause size={18} /> : <Play size={18} />}
          </Button>
          {audioUrl.value && (
            <audio controls src={audioUrl.value}>
              <track kind="captions" />
            </audio>
          )}
        </div>
        <div>
          <small>
            点击按钮或者同时按下 <kbd>{keys.key1}</kbd>+<kbd>{keys.key2}</kbd> 键
            {audio.status.value === "inactive" ? "开始" : audio.status.value === "recording" ? "完成" : "xx"}
            录音 ({audio.status.value})
          </small>
        </div>
      </div>
    );
  },
});

export default RecorderView;
